/*
   file : main.c
    服务端入口函数.
   University of Jiangsu
   memoryDB      2010.6
 */


#include "def_head.h"
#include "calc.h"

void signal_process()
{
//	printf("pthread %u will be closed\n",(unsigned)pthread_self());
	pthread_exit(NULL);
	return;
}

static void *doit_client(void *sockfd)
{
	struct sockaddr_in ss;
	socklen_t len=sizeof(ss);
	getpeername(*(int *)sockfd,(struct sockaddr *)&ss,&len);
	char client_ip[1024];
	inet_ntop(AF_INET,&ss.sin_addr,client_ip,sizeof(client_ip));
	in_port_t client_port=ss.sin_port;
	printf("new client connected,ip:%s,port:%d\n",client_ip,client_port);
		
	char receive[MAX_COMMAND];
	while(1){
		sql_sentence *sql=malloc(sizeof(sql_sentence));
		Init_sql(sql);
		sql->sockfd=*(int *)sockfd;

		bzero(receive,MAX_COMMAND);
		read(*(int *)sockfd,receive,MAX_COMMAND);
		if(!strcmp(receive,"bye;\n"))
		  break;
//		receive[strlen(receive)-1]=0;
		strcpy(sql->str,receive);
		//yy_switch_to_buffer(yy_scan_string(receive));
		parse(sql);	
		
		free(sql);	
	}
	close(*(int *)sockfd);
	return NULL;
}

static void *doit_server()
{
	char receive[MAX_COMMAND];
	while(1){
		sql_sentence *sql=malloc(sizeof(sql_sentence));
		
		Init_sql(sql);
		sql->sockfd=1;

		bzero(receive,MAX_COMMAND);
		printf("$:");		
		fgets(receive,MAX_COMMAND,stdin);
		if(!strcmp(receive,"\n"))
			continue;
		receive[strlen(receive)-1]=0;
		strcpy(sql->str,receive);
		//yy_switch_to_buffer(yy_scan_string(receive));
		parse(sql);
		
		free(sql);
	}
	return NULL;
}

int main()
{
	Init_DB_lock();
	int *connfd;
	struct sockaddr_in serveradd;

	if((listenfd=socket(AF_INET,SOCK_STREAM,0))==-1){
		printf("socket error:%d\n",errno);
		exit(0);
	}
	bzero(&serveradd,sizeof(serveradd));
	serveradd.sin_family=AF_INET;
	serveradd.sin_addr.s_addr=htonl(INADDR_ANY);
	serveradd.sin_port=htons(PORT);

	if(bind(listenfd,(struct sockaddr *)&serveradd,sizeof(serveradd))==-1){
		printf("bind error:%d\n",errno);
		exit(0);
	}
	if(listen(listenfd,1024)==-1){
		printf("listen error:%d\n",errno);
		exit(0);
	}

	signal(SIGPIPE,signal_process);
//	signal(SIGCHLD,SIG_IGN);
//	signal(SIGHUP,SIG_IGN);
//	signal(SIGINT,SIG_IGN);
	
	printf("##########server is running##########\n");
	pthread_t server_tid;
	pthread_create(&server_tid,NULL,doit_server,NULL);
		
	
	while(1){
		pthread_t client_tid;
		connfd=malloc(sizeof(int));
		*connfd=accept(listenfd,(struct sockaddr *)NULL,NULL);
		pthread_create(&client_tid,NULL,doit_client,connfd);
	}
    return 0;    
}
